import axios from "axios";

//导入nprogress进度条
import NProgress from  'nprogress'
import  'nprogress/nprogress.css'

const service = axios.create({
    baseURL:'http://127.0.0.1:8888/api/private/v1/',
    timeout:2000
});
//拦截请求
service.interceptors.request.use(
    config => {

    //开始进度条
    NProgress.start()
    //为请求头添加Token验证(Authorization:token)
     config.headers.Authorization =window.sessionStorage.getItem("vue_shop_token")
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//拦截响应
service.interceptors.response.use(
    response => {
     //结束进度条
       NProgress.done()
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    window.sessionStorage.removeItem("vue_shop_token")
                    this.$message.error("Token未授权");
                    router.push({name:"login"});
                    break;
                case 404:
                    console.log("请求的资源不存在")
                    this.$message.error("请求的资源不存在");
                    break;
                case 400:
                    this.$message.error("请求的地址不存在或者包含不支持的参数");
                    break;   
            }
        }
        return Promise.reject(error);
    }
);

export default service;
